package jacson;

import Domain.User;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

import java.io.File;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * MyUser: Александр
 * Date: 30.11.13
 * Time: 13:37
 * To change this template use File | Settings | File Templates.
 */
public class JacsonDemo {
    public static void main(String[] args) throws IOException {
        JsonFactory f = new JsonFactory();
        JsonGenerator g = f.createJsonGenerator(new File("D:\\Java\\Humster\\src\\main\\resources\\user.json"), JsonEncoding.UTF8);

        g.writeStartObject();
        g.writeObjectFieldStart("name");
        g.writeStringField("first","Stark");
        g.writeStringField("last","Jsoner");
        g.writeEndObject();
        g.writeStringField("gender", User.Gender.MALE.toString());
        g.writeBooleanField("verified",true);
        g.writeBinaryField("userImage",new String("favicon.ico").getBytes());
        g.writeEndObject();
        g.close();

    }

    private static void jsonNodeReader() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode rootNode = mapper.readTree(new File("D:\\Java\\Humster\\src\\main\\resources\\user.json"));
        JsonNode nameNode = rootNode.path("name");
        String name = nameNode.path("last").getTextValue();
        System.out.println(name);
        ((ObjectNode)nameNode).put("last", "jsoner");
        mapper.writeValue(new File("D:\\Java\\Humster\\src\\main\\resources\\user.json"),rootNode);
    }

    private static void writeData() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        User user = new User();
        user.getName().setFirst("Alex");
        user.getName().setLast("Radchykov");
        user.setGender(User.Gender.MALE);
        user.setVerified(true);
        mapper.writeValue(new File("D:\\Java\\Humster\\src\\main\\resources\\writed_data.json"),user);
    }

    public static User readData() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        User user = mapper.readValue(new File("D:\\Java\\Humster\\src\\main\\resources\\user.json"),User.class);
        System.out.println(user);
        return user;
    }
}
